package com.gs.common.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @title: 孙杨申
 * @date 2022/10/3 15:25
 */
@Component
public class MybatisPlusHandler implements MetaObjectHandler {
    private final static String UPDATE_TIME = "updateTime";

    // 乐观锁版本号
    private final static String VERSION = "version";

    @Override
    public void insertFill(MetaObject metaObject) {
        Date date = new Date();
        LocalDateTime now = LocalDateTime.now();
        strictInsertFill(metaObject, UPDATE_TIME, Date.class, date);
        strictInsertFill(metaObject, UPDATE_TIME, LocalDateTime.class, now);
        this.setFieldValByName(VERSION, 1, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Date date = new Date();
        LocalDateTime now = LocalDateTime.now();
        strictUpdateFill(metaObject, UPDATE_TIME, Date.class, new Date());
        //更新时间
        strictInsertFill(metaObject, UPDATE_TIME, LocalDateTime.class, now);

    }

    /**
     * IPage的分页使用的是拦截器，属于物理分页，好处就是处理大量数据时，查询速度快。
     *    有兴趣的同学可以看看什么是物理分页和逻辑分页。
     * @return
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //向Mybatis过滤器链中添加分页拦截器
        interceptor.addInnerInterceptor(new
                PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }
}